import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:whale/helper/utils/media_picker.dart';
import 'package:whale/helper/utils/popup/index.dart';
import 'package:whale/helper/utils/util.dart';

import '../../helper/utils/permisson.dart';
import '../../helper/utils/widget_to_image.dart';
import 'index.dart';

class PaintDemoController extends GetxController {
  PaintDemoController();

  final state = PaintDemoState();

  // tap
  void handleTap(int index) {
    Get.snackbar(
      "标题",
      "消息",
    );
  }

  void pickWaterImage() async {
    final data = await MediaPicker.pickImages(maxCount: 1);
    state.waterImage = data.first;
    update();
  }

  void addWaterText() async {
    final action = await Popup.bottomInput(
      title: '添加水印',
      onChanged: (value) {
        state.text = value;
      },
    );
    if (action == 1) {
      update();
    }
  }

  void saveWater() async {
    if (!(await PermissonMan.photos())) return;
    final img =
        await WidgetToImageUtils.imageLoader.getImageFromWidget(state.waterKey);
    final data = await img.toByteData(format: ImageByteFormat.png);
    if (data != null) {
      final u8l = data.buffer.asUint8List();

      final result = await ImageGallerySaver.saveImage(u8l, quality: 100);
      Hud.toast('保存到相册成功');
    }
  }

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    super.onInit();
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    super.onReady();
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    super.onClose();
  }

  /// dispose 释放内存
  @override
  void dispose() {
    super.dispose();
  }
}
